package com.lagou.tomcat.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 创建人: yyn
 * 创建时间:2021/9/4 23:23
 */
public class Response {

    private OutputStream outputStream;

    private Response() {
    }


    public static Response create(OutputStream outputStream) {
        Response response = new Response();
        response.outputStream = outputStream;
        return response;
    }


    public void print(HttpStatusEnum httpStatusEnum, String string) {
        String responseHand = httpStatusEnum.getResponseHand();
        String result = responseHand.replace("${length}", String.valueOf(string.length())) + string;
        System.out.println(result);
        try {
            outputStream.write(result.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void print(HttpStatusEnum httpStatusEnum, InputStream inputStream) {
        try {
            int count = 0;
            while (count == 0) {
                count = inputStream.available();
            }
            String head = httpStatusEnum.getResponseHand().replace("${length}", String.valueOf(count));
            outputStream.write(head.getBytes());
            long writeSize = 0;    //已读取长度
            int size = 1024;
            byte[] bytes = new byte[size];
            while (writeSize < count) {
                // 判断是否大于总长度
                if (writeSize + size > count) {
                    size = (int) (count - writeSize);
                    bytes = new byte[size];
                }
                inputStream.read(bytes);
                outputStream.write(bytes);
                outputStream.flush();
                writeSize += size;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
